<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\cms\controller;


use function PHPSTORM_META\type;
use think\admin\Controller;
use think\facade\Config;
use think\admin\service\AdminService;
use think\admin\extend\DataExtend;
use think\admin\service\MenuService;




/**
 * 培训报名管理
 * Class EduEnroll
 * @package app\wechat\controller
 */
class EduEnroll extends BaseController
{

    /**
     * 当前操作数据库
     * @var string
     */
    protected $table = 'CmsEduEnroll';
    static $PASS_STATE_OPTION = array(0=>"待考核",1=>"合格",2=>"不合格");
    public $CITY_OPTION = array("长沙","株洲","湘潭","益阳","衡阳","常德","岳阳","邵阳","娄底","永州","郴州","怀化","张家界","湘西自治州");

    /**
     * 培训报名管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {

        $this->title = "报名管理";
        $map = [];
        $query = $this->_query($this->table)->like('name,company,room_no')->where($map);

        $class_name = $this->request->get("class_name");
        if($class_name){
            $class_ids = $this->_query_data_ids($class_name, "CmsEduClass");
            $query = $query->whereIn("class_id",$class_ids);
        }

        $this->time_span = $this->request->get("time_span");
        if($this->time_span){
            $time_span = explode(" - ", $this->time_span);
            $query = $query->whereBetween("occur_time",[$time_span[0],$time_span[1]]);
        }
        $this->company = $this->request->get("company");
        $this->room_no = $this->request->get("room_no");


        $this->class=$this->app->db->name('CmsEduClass')
            ->order('id desc')->select()->toArray();

        $query->order('id desc')->page();
    }

    public function _query_data_ids($name, $tableName){
        $query = $this->app->db->name($tableName)->whereLike('name',"%".$name."%")
            ->field("id")->order('id desc')->select();
        $ids = array();
        for($i=0; $i<count($query); $i++){
            $ids[] = $query[$i]['id'];
        }
        return $ids;
    }

    protected function _index_page_filter(&$data)
    {

        $this->pass = self::$PASS_STATE_OPTION;
        $class_ids = $this->_getDataIds($data, "class_id");
        $class = $this->_getClassDict($class_ids);
        for($i=0; $i<count($data); $i++){
            $data[$i]['class_name'] = $class[$data[$i]['class_id']]['name'];
            $data[$i]['class_status'] = $class[$data[$i]['class_id']]['status'];
        }

    }

    protected function _getClassDict($class_ids){
        $map = array("id"=> $class_ids);
        $class = $this->app->db->name('CmsEduClass')->field("id,name,status")->where($map)->select();
        $result = array();
        for ($i=0; $i<count($class); $i++){
            $result[$class[$i]['id']] = $class[$i];
        }
        return $result;
    }

    protected function _getDataIds($data, $key){
        $arr = [];
        for ($i=0; $i<count($data); $i++){
            array_push($arr, $data[$i][$key]);
        }
        return $arr;
    }

    /**
     * 表单数据处理
     * @param array $vo
     * @throws \ReflectionException
     */
    protected function _form_filter(&$vo)
    {
        if ($this->request->isGet()) {
            // 清理权限节点
            AdminService::instance()->clearCache();

            if($vo){
                $this->enroll = $vo;
            }else{
                $this->enroll = array(
                    "name"=>"",
                    "idno"=>"",
                    "city"=>"",
                    "gender"=>"",
                    "company"=>"",
                    "avatar"=>"",
                    "phone"=>"",
                    "class_id"=>"",
                    "position_id"=>"",
                );
            }
            //查出所有正在报名的培训班信息
            $this->classes = $this->_get_class_enroll();
            for($i=0; $i<count($this->classes); $i++){
                if($this->classes[$i]['id']==$this->enroll['class_id'])
                    $this->class = $this->classes[$i];
                $this->classes[$i]['sub'] = $this->_get_work_ids($this->classes[$i]['position_ids']);
            }
            $this->classesJson = json_encode($this->classes);


            if(!property_exists($this, "class")){
                $this->class =  $this->app->db->name('CmsEduClass')->field("id,name,position_ids")
                    ->where(array("id"=>$this->enroll['class_id']))->find();
            }

            //$this->classes = array_merge($this->class,)
            if($vo && $this->class['position_ids']){
                $this->position = $this->_get_work_ids($this->class['position_ids']);
            }else{
                $this->position = [];
            }

        }
    }

    public function _get_class_enroll(){
        $map = array("status"=>1);
        return $this->app->db->name('CmsEduClass')->field("id,name,position_ids")->where($map)
            ->whereBetween("create_at",[ time()-6*30*24*3600, time() ])
            ->select()->toArray();
    }

    public function _get_work_ids($position_ids){
        $work_ids = [];
        $position = $this->app->db->name('CmsEduWork')->alias("wp")
            ->field("wp.*,ew.name as class_name, ew.id as class_id")
            ->join('cms_edu_work ew', "ew.id=wp.parent_id")
            ->whereIn("wp.id", $position_ids)
            ->order('wp.id desc')->select()->toArray();

        for($i=0; $i<count($position); $i++){
            if(array_key_exists($position[$i]['class_id'], $work_ids)==false){
                $work_ids[ $position[$i]['class_id'] ] = array(
                    "id" => $position[$i]['class_id'],
                    "name" => $position[$i]['class_name'],
                    "sub" => [],
                );
            }
        }

        for($i=0; $i<count($position); $i++){
            $work_ids[ $position[$i]['class_id'] ]['sub'][] = $position[$i];
        }
        return array_values($work_ids);
    }

    /**
     * 添加报名信息
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function add()
    {

        if ($this->request->isGet()) {
            $this->_applyFormToken();
            $this->_form($this->table, 'form');
        } else {

            $update = $this->request->post('data', []);
            $map = [ "position.id"=>$update['position_id'] ];
            $work= $this->app->db->name('CmsEduWork')->alias("position")
                ->field("position.*,work.name as work_name,work.id as work_id")
                ->join('cms_edu_work work', "position.parent_id=work.id")
                ->where($map)
                ->find();

            $update['no'] = $this->_generate_enroll_no($update);
            $update['work_id'] = $work['work_id'];
            $update['work_name'] = $work['work_name'];
            $update[ 'create_by']   = AdminService::instance()->getUserId();
            $update[ 'update_at'] = $update[ 'create_at'] = time();
            if ($this->app->db->name($this->table)->insert($update) !== false) {
                $this->success('添加成功！','javascript:history.back()');
            } else {
                $this->error('添加失败，请稍候再试！');
            }
        }
    }

    /**
     * 编辑报名信息
     * @auth true
     */
    public function edit()
    {


        $this->id = $this->request->get('id');
        $map = array("id" => $this->id);
        if (empty($this->id)) $this->error('参数错误，请稍候再试！');
        if ($this->request->isGet()) {
            if ($this->request->get('output') === 'json') {
                $this->success('获取数据成功！', $this->app->db->name($this->table)->where($map)->find());
            } else {
                $this->title = '编辑信息';
                $this->_applyFormToken();
                $this->_form($this->table, 'form');
            }
        }else{
            $data = $this->request->post('data', []);
            $data['update_at'] = time();
            if ($this->app->db->name($this->table)->where($map)->update($data) !== false) {
                $this->success('信息更新成功！', 'javascript:history.back()');
            } else {
                $this->error('信息更新失败，请稍候再试！');
            }
        }

    }

    /**
     * 修改班级信息
     * @auth true
     */
    public function editgroup()
    {

        if ($this->request->isGet()) {
            $this->id = $this->request->get('id');
            $map = array("id" => $this->id);
            $this->enroll = $this->app->db->name($this->table)->where($map)->find();
            $map2 = array("class_id"=>$this->enroll['class_id']);
            $this->groups = $this->app->db->name("CmsEduClassGroup")->where($map2)->select();
            $this->fetch();
        } else {
            $update = $this->request->post('data', []);
            $update[ 'update_at'] = $update[ 'create_at'] = time();
            if ($this->app->db->name($this->table)->save($update) !== false) {
                $this->success('更新成功！');
            } else {
                $this->error('更新失败，请稍候再试！');
            }
        }
    }

    /**
     * 删除报名信息
     * @auth true
     */
    public function remove()
    {
        $this->_delete($this->table);
    }

    /**
     * 导出报名信息
     * @auth true
     */
    public function export(){

        $className = $this->request->get("class_name");
        $stuName = $this->request->get("student_name");
        $timeSpan = $this->request->get("time_span");
        $company = $this->request->get("company");
        $room_no = $this->request->get("room_no");
        $title = [array("no","报名号"), array("class_name","班级名称"),
                    array("name","学员名称"),array("gender","性别"),array("idno","身份证"),array("phone","联系电话"),
                    array("work_name","工作岗位"),array("position_name","工种"),array("company","工作单位"),
                    array("city","所在市州"), array("occur_time","报名时间"), array("room_no","班级"),
                    array("seat_no","座位号"), array("hour","学时")];
        $data = $this->prepareExportData($stuName, $className, $timeSpan,$company,$room_no);
        $this->exportExcel($title, $data);

    }

    private function prepareExportData($stuName, $className, $timeSpan,$company,$room_no){

        $map = [];
        $query= $this->app->db->name('CmsEduEnroll');
        if($stuName) $query = $query->whereLike("ee.name","%".$stuName."%");
        if($className) $query = $query->whereLike("ec.name","%".$className."%");
        if($company) $query = $query->whereLike("ee.company","%".$company."%");
        if($room_no) $query = $query->whereLike("ee.room_no","%".$room_no."%");
        if($timeSpan){
            $timeSpan = explode(" - ", $timeSpan);
            $query = $query->whereBetween("occur_time",[$timeSpan[0],$timeSpan[1]]);
        }
        $res = $query ->alias("ee")
            ->field("ee.*,ec.name as class_name")
            ->join('cms_edu_class ec', "ec.id=ee.class_id")
            ->where($map)
            ->order('ee.id desc')
            ->select()->toArray();
        for($i=0; $i<count($res); $i++){
            $res[$i]['pass'] = self::$PASS_STATE_OPTION[ intval($res[$i]['is_pass']) ];
        }
        return $res;
    }

    /**
     * 导入分班信息
     * @auth true
     */
    public function importGroup(){
        //$inputFileName = "F:\\phpStudy\\GasPortalProject\\temp\\01simple.xlsx";
        //$inputFileName = "http://127.0.0.1:9500/upload/63/1fcfb478ee9a562f929784a1b44e64.xlsx";
        $inputFileName = $this->request->request("url");
        $inputFileName = $this->filerFilePath($inputFileName);

        $fields = [ "no", "name", "room_no", "seat_no" ];
        $data = $this->getImportDataFromExcel($inputFileName, $fields);
        if($data==false){
            $this->error("没有数据需要被导入");
        }

        for ($i=0; $i<count($data); $i++) {
            $map['no'] = $data[$i]['no'];
            $map['name'] = $data[$i]['name'];
            $enroll = $this->app->db->name($this->table)->where($map)->find();
            if($enroll==false){
                $this->error("报名号：".$map['no']."与姓名：".$map['name']."不匹配");
            }
            $map = array("class_id"=>$enroll['class_id'],"name"=>$data[$i]['room_no']);
            $group = $this->app->db->name("CmsEduClassGroup")->where($map)->find();
            if(!$group){
                $this->error($this->app->db->name("CmsEduClassGroup")->getLastSql());
                //$this->error("班级信息：".$data[$i]['room_no']."不存在");
            }else{
                $data[$i]['room_id'] = $group['id'];
            }
        }

        for ($i=0; $i<count($data); $i++) {
            $map = ['no' => $data[$i]['no'] ] ;
            $to_update = [
                'update_at' => time(),
                'room_id' => $data[$i]['room_id'],
                'room_no' => $data[$i]['room_no'],
                "seat_no"=> $data[$i]['seat_no']
            ];
            $this->app->db->name($this->table)->where($map)->update($to_update);
        }

        $this->success("导入成功");

    }

    /**
     * 导入报名信息
     * @auth true
     */
    public function importEnroll(){
        //$inputFileName = "F:\\phpStudy\\GasPortalProject\\temp\\01simple.xlsx";
        //$inputFileName = "http://127.0.0.1:9500/upload/63/1fcfb478ee9a562f929784a1b44e64.xlsx";
        $inputFileName = $this->request->request("url");
        $inputFileName = $this->filerFilePath($inputFileName);

        //读取数据源
        $fields = [
            "class_id","name","gender","city","company",
            "idno", "work_name","position_name","phone"
        ];
        //$fields = [ "class_id","name","gender","idno","phone","company", "work_name","position_name","avatar" ];
        $data = $this->getImportDataFromExcel($inputFileName, $fields);
        if($data==false){
            $this->error("没有数据需要被导入");
        }

        //有效性检查
        for ($i=0; $i<count($data); $i++) {
            if($data[$i]['name']==false || $data[$i]['idno']==false){
                //无效的数据
                continue;
            }

            if(strlen($data[$i]['idno'])!=18){
                $this->error("第".($i+2)."行数据有误,身份证:".$data[$i]['idno']."格式有误");
            }

            if(strlen($data[$i]['phone'])!=11){
                $this->error("第".($i+2)."行数据有误,手机号:".$data[$i]['phone']."格式有误");
            }

            $map = [ "idno"=>$data[$i]['idno'], "class_id"=> $data[$i]['class_id'] ];
            if($this->app->db->name("CmsEduEnroll")->where($map)->find()){
                $this->error($data[$i]['name']."(".$data[$i]['idno'].")已经报名该培训班，请不要重复报名");
            }

            $map = ["name"=>$data[$i]['class_id']];
            $class = $this->app->db->name("CmsEduClass")->field("id,name")->where($map)->find();
            if($class==null){
                $this->error("培训班名称：".$data[$i]['class_id']."无效");
            }else{
                $data[$i]['class_id'] = $class['id'];
            }

            $map = [ "wp.name"=>$data[$i]['work_name'], "ew.name"=>$data[$i]['position_name'] ];
            $work = $this->app->db->name('CmsEduWork')->alias("wp")
                ->field("wp.id as work_id, wp.name as work_name,ew.name as position_name, ew.id as position_id")
                ->join('cms_edu_work ew', "wp.id=ew.parent_id")
                ->where($map)
                ->order('wp.id desc')->find();
            if($work==false){
                $this->error("岗位:".$data[$i]['work_name']."及工种:".$data[$i]['position_name']."信息填写有误");
            }
            $data[$i]['work_id'] = $work['work_id'];
            $data[$i]['position_id'] = $work['position_id'];
            $data[$i]['occur_time'] = date("Y-m-d");
        }

        //写入数据
        for ($i=0; $i<count($data); $i++) {
            $data[$i]['no'] = $this->_generate_enroll_no($data[$i]);
            $this->app->db->name($this->table)->save($data[$i]);
        }

        $this->success("导入成功");

    }

    public function _generate_enroll_no($student){
        $data = array(
            "idno" => $student['idno'],
            "name" => $student['name'],
            "phone" => $student['phone'],
        );
        return $this->app->db->name("CmsEduEnrollNo")->insertGetId($data);
    }

    /**
     * 管理岗位及工种
     * @auth true
     */
    public function work(){

    }

}
